package com.tubruk.trackme;

import java.io.File;
import java.util.ArrayList;

import com.tubruk.adapter.FileAdapter;
import com.tubruk.object.FileWrapper;
import com.tubruk.object.Global;

import android.app.Activity;
import android.os.Bundle;

import android.content.Context;
import android.content.Intent;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.TableLayout;
import android.widget.TextView;
import android.widget.AdapterView.OnItemClickListener;
 
public class FileBrowser extends Activity {
	
	
       
		private ListView filelist;
        private ArrayList<FileWrapper> directoryEntries = new ArrayList<FileWrapper>();
        private File currentDirectory = new File("/");
 
        public static final String RESULT_PATH 		= "RESULT_PATH";
        public static final String MODE_TYPE		= "MODE_TYPE";
        
        //put extra with integer does not seem to work, so.....
        public static final String MODE_BROWSE				 	= "0"; //default
        public static final String MODE_BROWSE_ADDNEWFILE		= "1";
        
        private String mode;
        
        /** Called when the activity is first created. */
        @Override
        public void onCreate(Bundle bundle) {
                super.onCreate(bundle);
                
                mode = FileBrowser.MODE_BROWSE;
                Bundle extras = getIntent().getExtras(); 
        		if(extras !=null)
        		{
        			mode = extras.getString(FileBrowser.MODE_TYPE);
        		}
                
        		if (mode.equals(FileBrowser.MODE_BROWSE_ADDNEWFILE)){
    				setContentView(R.layout.addnewfile);
    				
    				Button addnew = (Button) findViewById(R.id.addnew);
    				addnew.setOnClickListener(new AddNewFileClickListener());
    			}else {
    				setContentView(R.layout.filemanager);
    			}
        		
        		filelist = (ListView) findViewById(R.id.fileList);
                
                browseToRoot();
             
                ImageButton locate = (ImageButton) findViewById(R.id.locate);
        		locate.setOnClickListener(new ActionClickListener(FileBrowser.this, TrackMapActivity.class));
        		
        		ImageButton search = (ImageButton) findViewById(R.id.search);
        		search.setOnClickListener(new ActionClickListener(FileBrowser.this, History.class));

        	}
        
        	private class AddNewFileClickListener implements OnClickListener {

				@Override
				public void onClick(View v) {
					// TODO Auto-generated method stub
					EditText et = (EditText) findViewById(R.id.newfile);
					String filepath = et.getText().toString();
					if (filepath != null && !filepath.equals("")){
						String tmp = FileBrowser.this.currentDirectory.getAbsolutePath();
						if (tmp.charAt(tmp.length()-1) == '/'){
							filepath = tmp + filepath;
						}else {
							filepath = tmp + "/" + filepath;
						}
						filepath = filepath.trim();
						
						
						File f = new File(filepath);
						//do not overwrite
						if (!f.exists()){
							Intent resultIntent = new Intent();
		                	resultIntent.putExtra(FileBrowser.RESULT_PATH, filepath);
		                	setResult(Activity.RESULT_OK, resultIntent);
		                	finish();
						}
					}
				}
        		
        	}
        	
        	private class ActionClickListener implements OnClickListener {
        		private Class<?> target;
        		private Context source;
        		
        		public ActionClickListener(Context source, Class<?> target){
        			this.source = source;
        			this.target = target;
        		}
        		
        		public void onClick(View v) {
        			finish();
        			Intent i = new Intent(source, target);
        			startActivity(i);
        		}
        		
        	}
       
        /**
         * This function browses to the
         * root-directory of the file-system.
         */
        private void browseToRoot() {
                browseTo(new File("/"));
    }
       
        /**
         * This function browses up one level
         * according to the field: currentDirectory
         */
        private void upOneLevel(){
                if(this.currentDirectory.getParent() != null)
                        this.browseTo(this.currentDirectory.getParentFile());
        }
       
        private void browseTo(final File aDirectory){
                if (aDirectory.isDirectory()){
                        this.currentDirectory = aDirectory;
                        fill(aDirectory.listFiles());
                }else{
                	if (mode.equals(FileBrowser.MODE_BROWSE)){
	                	//need to set result and finish();
	                	Intent resultIntent = new Intent();
	                	resultIntent.putExtra(FileBrowser.RESULT_PATH, aDirectory.getAbsolutePath());
	                	setResult(Activity.RESULT_OK, resultIntent);
	                	finish();
                	}
                }
        }
 
        private void fill(File[] files) {
                this.directoryEntries.clear();
               
                // Add the "." and the ".." == 'Up one level'
                try {
                        Thread.sleep(10);
                } catch (InterruptedException e1) {
                        // TODO Auto-generated catch block
                        e1.printStackTrace();
                }
                this.directoryEntries.add(new FileWrapper("."));
               
                if(this.currentDirectory.getParent() != null)
                        this.directoryEntries.add(new FileWrapper(".."));
               
                if(files != null) {
	                for (File file:files){
	                	FileWrapper wrapper = new FileWrapper(file.getName());
	                	wrapper.setFile(file);
	                	this.directoryEntries.add(wrapper);
	                }
                }
                
                /*
                ArrayAdapter<String> directoryList = new ArrayAdapter<String>(this,
                                R.layout.file_row, this.directoryEntries);
               */
                
                FileAdapter directoryList = new FileAdapter (this,R.layout.file_row, this.directoryEntries);
                
                filelist.setAdapter(directoryList);
                filelist.setOnItemClickListener( new BrowseItemListener());
                
        }
        
        private class BrowseItemListener implements OnItemClickListener {

			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
					long arg3) {
				int selectionRowID = (int) filelist.getSelectedItemId();
				
				Log.d("SELECTED: ", selectionRowID + "");
				
                String selectedFileString = ""; 
                FileWrapper wrapper = FileBrowser.this.directoryEntries.get(selectionRowID);
                
                selectedFileString = wrapper.getName();
                if (selectedFileString.equals(".")) {
                        // Refresh
                	FileBrowser.this.browseTo(FileBrowser.this.currentDirectory);
                } else if(selectedFileString.equals("..")){
                	FileBrowser.this.upOneLevel();
                } else {
                        File clickedFile = wrapper.getFile();
                        
                        
                        if(clickedFile != null)
                        	FileBrowser.this.browseTo(clickedFile);
                }

			}
        	
        }
}
